<?php
/**
 * Created by PhpStorm.
 * User: zhanglei
 * Date: 2018/5/11
 * Time: 8:33
 */

namespace app\admin\model;

use app\admin\model\GoodsImage as GoodsImageModel;
use app\admin\model\GoodsSpecItem as GoodsSpecItemModel;
use app\admin\model\GoodsSpecPrice as GoodsSpecPriceModel;

class Goods extends BaseModel
{
    //商品,商品相册的关联模型
    public function goodsImage(){
        return $this->hasMany('GoodsImage','goods_id','id');
    }

    //商品管理商品模型
    public function goodsModel()
    {
        return $this->belongsTo('GoodsModel', 'goods_id', 'id'); // TODO: Change the autogenerated stub
    }

    //添加时调用的事务处理方法
    public function addGoods($params,$tag=false)
    {
        $this->startTrans();
        $res = $this->allowField(true)->isUpdate($tag)->save($params);
        if($res === false){
            $this->rollback();
            return ['error'=>1,'msg'=>'操作失败'];
        }

        if(!empty($params['model_price'])){
            $goodsSpecPrice = new GoodsSpecPriceModel();
            $goodsSpecPrice->startTrans();
            if($tag){
                $goodsSpecPrice->where(['goods_id'=>$params['id']])->delete();
            }
            $model_price = [];
            foreach($params['model_price'] as $k=>$v){
                $model_price[$k]['spec_item_ids'] = $k;
                $model_price[$k]['price'] = $v;
                $model_price[$k]['goods_id'] = $this->id;
                $model_price[$k]['spec_item_names'] = $this->getSpecItemNames($k,'_');
            }

            $res = $goodsSpecPrice->allowField(true)->isUpdate(false)->saveAll($model_price);
            if($res === false){
                $goodsSpecPrice->rollback();
                return ['error'=>1,'msg'=>'模型操作失败!'];
            }
            $goodsSpecPrice->commit();
        }

        if(!empty($params['url'])){
            $goodsImage = [];
            foreach($params['url'] as $k=>$v){
                $goodsImage[$k]['url'] = $v;
                $goodsImage[$k]['origin'] = $params['tag'];
                $goodsImage[$k]['goods_id'] = $this->id;
            }
            $goodsImageModel = new GoodsImageModel();
            $goodsImageModel->startTrans();
            $res = $goodsImageModel->allowField(true)->isUpdate(false)->saveAll($goodsImage);
            if($res === false){
                $goodsImageModel->rollback();
                return ['error'=>1,'msg'=>'商品图片添加失败'];
            }
            $goodsImageModel->commit();
        }
        $this->commit();
        return ['error'=>0,'msg'=>'操作成功'];
    }

    //
    private function getSpecItemNames($str,$delim)
    {
        $arr = explode($delim,$str);
        $res = '';
        foreach($arr as $k=>$v){
            if(!empty($v)){
                $specItem = GoodsSpecItemModel::find($v);
                $res .= '_'.$specItem->getData('name');
            }
        }
        return $res;
    }


}